<template>
  <!-- 头像上传组件 -->
  <div class="avatar-container">
    <a-upload
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :before-upload="beforeUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="100%" />
      <div v-else>
        <a-icon type="plus" />
        <div class="ant-upload-text">选择头像</div>
      </div>
    </a-upload>
  </div>
</template>

<script>
import requests from "../js/requests.js";
import { Upload, Icon } from "ant-design-vue";

export default {
  name: "ChangeAvatar",
  components: { AUpload: Upload, AIcon: Icon },
  data() {
    return {
      imageUrl: "",
      avatarFile: null,
    };
  },
  mounted() {
    // 绑定自定义事件，当Modal父组件点击确认按钮时触发
    this.$on("handleUpload", this.handleUpload);
  },
  methods: {
    // 上传头像前的验证
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("只能上传jpeg或png类型的图片!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片不能大于2MB!");
      }
      if (isJpgOrPng && isLt2M) {
        this.avatarFile = file;
        // 将内存的文件对象转换成URL，使其显示在页面上进行预览
        this.imageUrl = window.URL.createObjectURL(file);
      }
      return false;
    },
    // 上传头像
    handleUpload() {
      // 如果已经选择了图片，则上传头像图片
      if (this.avatarFile) {
        // 将正在上传的状态传递给Modal父组件,使其显示加载动画
        this.$emit("getAvatarLoading", true);
        const formData = new FormData();
        formData.append("avatarFile", this.avatarFile);
        requests.uploadAvatar(formData).then((res) => {
          if (res.code == 200) {
            this.$emit("getAvatarLoading", false);
            this.$store.dispatch("setAvatarPath", res.data.avatarPath);
            this.$message.success(res.msg);
          } else {
            this.$emit("getAvatarLoading", false);
            this.$message.error(res.msg);
          }
        });
      } else {
        this.$message.error("请选择图片！");
      }
    },
  },
};
</script>

<style scoped>
.avatar-uploader {
  display: block;
  width: 102px;
  margin: 0 auto;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>